package com.crealth.handler;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.db.LoanAmountCalculatedDb;
import com.crealth.memcached.UserCached;
import com.crealth.model.LoanAmountCalculatedModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;

public class LoanAmountCalculatedHandler {
	
	public static NetMessageData obtainAllAmountCalculated(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		//JSONObject msgJson = revData.getRevDataMsgJson();
		/*int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Deputy_General_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}*/
		
		List<LoanAmountCalculatedModel> calculatedls = LoanAmountCalculatedDb.selectAllLoanAmountCalculated();
		JSONArray jsonArray = new JSONArray();
		for (LoanAmountCalculatedModel calculated : calculatedls) {
			jsonArray.add(calculated.toJSONObject());
		}
		
		resJson.put("resCode", 0);
		resJson.put("calculatedls", jsonArray);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData saveAllAmountCalculated(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Head_Manager) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		String calculatedls = msgJson.getString("calculatedls");
		JSONArray jsonArray = JSONArray.parseArray(calculatedls);
		if (jsonArray != null && jsonArray.size() > 0) {
			JSONArray resJsonArr = new JSONArray();
			for (int i = 0; i < jsonArray.size(); ++i) {
				JSONObject json = jsonArray.getJSONObject(i);
				LoanAmountCalculatedModel calculated = new LoanAmountCalculatedModel();
				calculated.parseFromJson(json);
				if (calculated.getId() > 0) {
					LoanAmountCalculatedDb.updateLoanAmountCalculatedByID(calculated);
					resJsonArr.add(calculated.toJSONObject());
				}
				else {
					LoanAmountCalculatedDb.insertLoanAmountCalculated(calculated);
					if (calculated.getId() > 0) {
						resJsonArr.add(calculated.toJSONObject());
					}
				}
			}
			resJson.put("calculatedls", resJsonArr);
		}
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
}
